#include "fileprocess.h"

FileProcess::FileProcess()
{

}

void FileProcess::fileWrite(QVariant address,QVariant str)
{
    QFile file(address.toString());
    if(file.open(QIODevice::WriteOnly))
    {
        file.write(str.toString().toUtf8());
    }

    file.close();
}

QList<QString> FileProcess::fileRead(QVariant address)
{
    QFile file(address.toString());
    QList<QString> fileContent;
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream stream(&file);  //用文件构造流
        while(!stream.atEnd())
        {
            QString str = stream.readLine();
            fileContent.append(str);
        }

    }
    file.close();
    return fileContent;
}

QString FileProcess::update(QList<QString> fileContent, QVariant userName, QVariant score)
{
    int count = fileContent.count();
    QString content = "";
    QStringList textList;
    QStringList scoreList;

    int judge=100;
    for (int i = 0; i < count; i++)
    {
        textList = fileContent.at(i).split(QRegExp("\\s+"),QString::SkipEmptyParts);
        scoreList.append(textList.at(1));

    }

    for(int i = 0; i < scoreList.count(); i++)
    {
        if(score > scoreList.at(i))
        {
            judge=i;
            break;
        }

    }
    for (int i = 0; i < count; i++)
    {
        if(i<judge)
        {
            content = content + fileContent.at(i) + "\n";
        }
        if(i==judge)
        {
            content = content + userName.toString()+ "\t" + "\t" + score.toString() + "\n";
        }
        if(i>judge)
        {
            content = content + fileContent.at(i-1) + "\n";
        }

    }

    if(count < 10&&count > 0)
    {
        if(judge < 9)
            content = content+ fileContent.at(count-1);
        if(judge > count)
            content = content + userName.toString()+ "\t" + "\t" + score.toString() + "\n";
    }
    if(count == 0)
    {
        content = content+ userName.toString()+ "\t" + "\t" + score.toString();
    }
    return content;
}
